package com.cloudcc.boot.security;

import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class ApiKeyRouter {

    private final Map<String, ApiKeyConfig> prefixToConfig = new HashMap<>();

    private final AntPathMatcher matcher = new AntPathMatcher();

    public ApiKeyRouter(Map<String, ApiKeyConfig> systemConfigs) {
        systemConfigs.forEach((sys, cfg) -> {
            if (cfg.isEnableAuth()) {
                cfg.getPaths().forEach(pattern -> prefixToConfig.put(pattern, cfg));
            }
        });
    }

    public Optional<ApiKeyConfig> match(String requestUri) {
        return prefixToConfig.entrySet().stream()
                .filter(entry -> matcher.match(entry.getKey(), requestUri))
                .map(Map.Entry::getValue)
                .findFirst();
    }

}
